package com.meepo.feed.old.video.shortvideo

import android.os.Bundle
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.meepo.basic.components.ImageLoaderFactory
import com.meepo.basic.components.listfragment.MeepoListFragment
import com.meepo.basic.schema.common.PageResult
import com.meepo.basic.schema.common.ResponseWrapper
import com.meepo.basic.schema.feed.Item
import com.meepo.feed.API
import com.meepo.feed.R
import com.meepo.framework.design.recycler.ViewHolder
import io.reactivex.Observable

class ShortVideoListFragment : MeepoListFragment<Item>() {

    private lateinit var mPlayerListManager: PlayerListManager

    override fun initView(view: View, savedInstanceState: Bundle?) {
        super.initView(view, savedInstanceState)

//        StatusBarUtil.setTranslucent(requireActivity())

        mPlayerListManager = PlayerListManager(requireActivity())

        // todo 优化
        getRecyclerView().addOnChildAttachStateChangeListener(object :
            RecyclerView.OnChildAttachStateChangeListener {
            override fun onChildViewAttachedToWindow(view: View) {}
            override fun onChildViewDetachedFromWindow(view: View) {
                view.findViewById<FrameLayout>(R.id.player_container)?.let {
                    val v = it.getChildAt(0)
                    mPlayerListManager.releaseIfDetachedFromWindow(v)
                }
            }
        })
    }

    override fun bind(item: Item, holder: ViewHolder, position: Int) {
        // 封面
        holder.setImagePath(
            R.id.thumb,
            item.findOneCover(),
            ImageLoaderFactory.getImageLoader(requireContext(), 500)
        )
        // 标题
        holder.getView<TextView>(R.id.title_tv)?.let {
            it.text = item.title
        }

        holder.getView<FrameLayout>(R.id.player_container)?.setOnClickListener {
            mPlayerListManager.play(position, item, holder)
        }
    }

    override fun onPause() {
        super.onPause()
        mPlayerListManager.pause()
    }

    override fun onSupportInvisible() {
        super.onSupportInvisible()
        mPlayerListManager.pause()
    }

    override fun getItemViewLayoutId(item: Item, position: Int): Int =
        R.layout.video_short_list_item_controller_layout

    override fun getItemSkeletonViewLayoutId(): Int = R.layout.default_item_skeleton_layout
    override fun loadDataObservable(page: Int): Observable<ResponseWrapper<PageResult<Item>>> {
        return API.instance().fetchShortVideos("")
    }

}